package com.yisu.expressway.onedollar.activity;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.will.network.images.round.CircleImageView;
import com.yisu.expressway.R;
import com.yisu.expressway.login.LoginManager;
import com.yisu.expressway.login.LoginPageActivity;
import com.yisu.expressway.onedollar.OneDollarConstants;
import com.yisu.expressway.onedollar.adapter.JoinRecordAdapter;
import com.yisu.expressway.onedollar.model.BuyNumConfigObj;
import com.yisu.expressway.onedollar.model.GoodsInfoObj;
import com.yisu.expressway.onedollar.model.OrderObj;
import com.yisu.expressway.onedollar.model.WinningRecord;
import com.yisu.expressway.onedollar.presenter.IGoodsPurchasePresenter;
import com.yisu.expressway.onedollar.presenter.impl.GoodsPurchasePresenterImpl;
import com.yisu.expressway.onedollar.utils.DateUtil;
import com.yisu.expressway.onedollar.view.IPurchaseView;
import com.yisu.expressway.onedollar.widget.CountdownView;
import com.yisu.expressway.onedollar.widget.DownUpPopupWindow;
import com.yisu.expressway.onedollar.widget.NoScrollListView;
import com.yisu.expressway.onedollar.widget.ODIndexSlideShowView;
import com.yisu.expressway.onedollar.widget.ObservableScrollView;
import com.yisu.expressway.onedollar.widget.TitleView;
import com.yisu.expressway.onedollar.widget.addandsub.AddAndSubView;
import com.yisu.expressway.onedollar.widget.addandsub.JoinAddAndSubView;
import com.yisu.expressway.utils.HBLog;
import com.yisu.expressway.utils.SpannableUtil;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Kaven on 2016/12/9.
 */

public class GoodsPurchaseActivity extends BasicActivity
        implements IPurchaseView, CountdownView.OnCountdownEndListener,
        CountdownView.OnCountdownIntervalListener, ObservableScrollView.ScrollViewListener {
    private static final String EXTRA_KEY_GOODS_NO = "extra_key_goods_no";
    private static final String TAG = GoodsPurchaseActivity.class.getSimpleName();
    @Bind(R.id.rootView)
    protected View mRootView;
    @Bind(R.id.scrollView)
    protected ObservableScrollView mScrollView;
    @Bind(R.id.title_bar)
    protected TitleView mTitleView;
    @Bind(R.id.slide_pic)
    protected ODIndexSlideShowView mPicSlideView;
    @Bind(R.id.tv_goods_name)
    protected TextView mGoodsNameTv;
    @Bind(R.id.tv_goods_des)
    protected TextView mGoodsDesTv;
    @Bind(R.id.tv_periodsnum)
    protected TextView mPeriodsNumTv;
    @Bind(R.id.progressBar)
    protected ProgressBar mProgressBar;
    @Bind(R.id.tv_total)
    protected TextView mTotalTv;
    @Bind(R.id.tv_remain)
    protected TextView mRemainTv;
    @Bind(R.id.ll_order_record)
    protected View mOrderRecordView;
    @Bind(R.id.tv_join_start)
    protected TextView mJoinStartTv;
    @Bind(R.id.listView)
    protected NoScrollListView mJoinRecordList;
    @Bind(R.id.ll_countdown)
    protected View mCountDownLl;
    @Bind(R.id.cv_countdown)
    protected CountdownView mCountDownCv;
    @Bind(R.id.rl_bottom)
    protected View mBottomView;
    @Bind(R.id.tv_buy_now)
    protected TextView mBuyNowTv;
    @Bind(R.id.tv_go)
    protected TextView mGoTv;
    @Bind(R.id.ll_winningrecord)
    protected View mWinningRecordView;
    @Bind(R.id.iv_cover)
    protected CircleImageView mAvatarView;
    @Bind(R.id.tv_record_winner)
    protected TextView mRecordWinnerTv;
    @Bind(R.id.tv_record_periodsnum)
    protected TextView mRecordPeriodNoTv;
    @Bind(R.id.tv_record_joinnum)
    protected TextView mRecordJoinNoTv;
    @Bind(R.id.tv_record_announcetime)
    protected TextView mRecordAnnounceTimeTv;
    @Bind(R.id.tv_record_lucknum)
    protected TextView mRecordLuckNoTv;

    private IGoodsPurchasePresenter mPresenter;
    private DownUpPopupWindow mDownUpPopupWindow;
    private View mPopMenuView;

    public static void launch(Context context, long goodsNo) {
        Intent intent = new Intent(context, GoodsPurchaseActivity.class);
        intent.putExtra(EXTRA_KEY_GOODS_NO, goodsNo);
        context.startActivity(intent);
    }

    //get StatusBar Height
    public static int getStatusBarHeight(Activity activity) {
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        return frame.top;
    }

    @OnClick({ R.id.rl_goods_detail, R.id.rl_orderShow, R.id.rl_recent, R.id.tv_buy_now,
            R.id.tv_record_lucknum_detail, R.id.tv_go })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_goods_detail:
                jump2CommodityDetailPage();
                break;
            case R.id.rl_orderShow:
                jump2OrderShowListPage();
                break;
            case R.id.rl_recent:
                jump2RecordHistoryListPage();
                break;
            case R.id.tv_buy_now:
                if (LoginManager.isLoggedIn()) {
                    showPopDlg();
                } else {
                    jump2LoginPage();
                }

                break;
            case R.id.tv_record_lucknum_detail:
                jump2LuckyNoIntroPage();
                break;
            case R.id.tv_go:
                jump2NextPage();
                break;
            default:
                break;
        }
    }

    @Override
    protected int getInflateLayoutId() {
        return R.layout.activity_goods_purchase;
    }

    @Override
    protected void initPresenter() {
        mPresenter = new GoodsPurchasePresenterImpl(this, this);
        mPresenter.init();
    }

    @Override
    protected void releasePresenter() {
        if (mPresenter != null) {
            mPresenter = null;
        }
    }

    @Override
    protected void getIntentData(Intent intent) {
        long goodsNo = intent.getLongExtra(EXTRA_KEY_GOODS_NO, -1);
        if (goodsNo < 0) {
            finish();
        }
        mPresenter.fetchGoodsInfo(goodsNo);
    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews() {
        mRootView.setVisibility(View.GONE);
    }

    @Override
    protected void bindEvents() {
        mTitleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {
                finish();
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {

            }
        });
        mScrollView.setScrollViewListener(GoodsPurchaseActivity.this);

    }

    @Override
    protected boolean isNeedLogin() {
        return false;
    }

    @Override
    protected void onLoginStateChange(boolean login) {

    }

    @Override
    public void showToast(String toastMsg) {
        if (StringUtil.isNullOrEmpty(toastMsg)) {
            return;
        }
        ToastUtil.displayLongToastMsg(this, toastMsg);
    }

    @Override
    public void showPopDlg() {
        final GoodsInfoObj goodsInfo = mPresenter.getGoodsInfo();
        if (goodsInfo == null || goodsInfo.salesGoods == null
                || goodsInfo.salesGoods.goodsNo <= 0) {
            return;
        }

        if (mDownUpPopupWindow == null) {
            mPopMenuView= getLayoutInflater().inflate(R.layout.popwindow_down_up, null);
            mDownUpPopupWindow = new DownUpPopupWindow(this, mPopMenuView);
        }
        mDownUpPopupWindow.showAtLocation(mTitleView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,
                0);
        mDownUpPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                dismissPopDlg();
            }
        });
        setJoinView(goodsInfo);
    }

    private void setJoinView(final GoodsInfoObj goodsInfo) {
        if (mPopMenuView == null){
            return;
        }
        TitleView titleView = (TitleView) mPopMenuView.findViewById(R.id.title_bar);
        titleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {

            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {
                dismissPopDlg();
            }
        });
        final JoinAddAndSubView joinAddAndSubView = (JoinAddAndSubView) mPopMenuView.findViewById(R.id.add_sub_view);
        joinAddAndSubView.setGoodsNo(goodsInfo.salesGoods.goodsNo);
        joinAddAndSubView.setOnBuyConfigListener(new JoinAddAndSubView.OnBuyConfigListener() {
            @Override
            public void onBuyConfigGet(boolean bSuc, BuyNumConfigObj configObj) {
                HBLog.d(TAG, "<onBuyConfigGet> ");
                if (configObj != null) {
                    if (joinAddAndSubView.getCount() > configObj.maxLimit - configObj.haveBuyNum
                        - 1) {
                        showToast("您已达到今日参与上限，明天再来看看吧~");
                    }
                }
            }
        });
        TextView name = (TextView) mPopMenuView.findViewById(R.id.tv_name);
        name.setText(goodsInfo.salesGoods.goodsName);
        TextView des = (TextView) mPopMenuView.findViewById(R.id.tv_des);
        des.setText(goodsInfo.salesGoods.desc);
        ImageView cover = (ImageView) mPopMenuView.findViewById(R.id.iv_cover);
        String goodspic = goodsInfo.salesGoods.goodsPic;
        if (!TextUtils.isEmpty(goodspic)) {
            String[] split = goodspic.split(",");
            if (split.length > 0) {
                String picShow = split[0];
                Glide.with(this).load(picShow).asBitmap().placeholder(R.drawable.pic_loading)
                    .diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop()
                    .animate(R.anim.fade_in_image).into(cover);
            }
        } else {
            cover.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
        }
        joinAddAndSubView.setTotal((int) goodsInfo.salesGoods.totalJoinNum);
        joinAddAndSubView.setRemain((int) goodsInfo.salesGoods.surplusJoinNum);
        joinAddAndSubView.setPrice(goodsInfo.salesGoods.price);
        joinAddAndSubView.setOnCountChangedListener(new AddAndSubView.OnCountChangedListener() {
            @Override
            public void onCountChanged(int count) {
                HBLog.d(TAG, "<onCountChanged> count is " + count);
                BuyNumConfigObj buyNumConfig = joinAddAndSubView.getBuyNumConfig();
                if (buyNumConfig != null) {
                    if (count >= buyNumConfig.maxLimit - buyNumConfig.haveBuyNum - 1) {
                        joinAddAndSubView.setEnabled(false);
                    } else {
                        joinAddAndSubView.setEnabled(true);
                    }
                }

            }

            @Override
            public void onBunNowClicked(double amount, int count) {
                HBLog.d(TAG, "<onBunNowClicked> amount is " + amount);
                BuyNumConfigObj buyNumConfig = joinAddAndSubView.getBuyNumConfig();
                if (buyNumConfig != null) {
                    if (count == 0) {
                        return;
                    }
                    if (count >= buyNumConfig.goodsMaxBuyNum - 1) {
                        showToast("超过最大购买次数");
                        return;

                    }
                    if (count >= buyNumConfig.remindValue - buyNumConfig.haveBuyNum - 1) {
                        showToast("今天已经投入不少了呢，请您理性投入，细水长流哦~");
                        return;
                    }
                    if (count >= buyNumConfig.maxLimit - buyNumConfig.haveBuyNum - 1) {
                        showToast("您已达到今日参与上限，明天再来看看吧~");
                        return;
                    }
                    mPresenter.createOrder(goodsInfo.salesGoods.goodsName,
                            goodsInfo.salesGoods.barcode, goodsInfo.salesGoods.periodsNum, amount,
                            count, goodsInfo.salesGoods.goodsNo);
                }

            }
        });
    }

    @Override
    public void dismissPopDlg() {
	    if (mDownUpPopupWindow != null ) {
		    if (mDownUpPopupWindow.isShowing()){
			    mDownUpPopupWindow.dismiss();
		    }
		    mDownUpPopupWindow = null;
		    mPopMenuView = null;
	    }
    }

    @Override
    public void jump2CommodityDetailPage() {
        GoodsInfoObj goodsInfo = mPresenter.getGoodsInfo();
        if (goodsInfo != null && goodsInfo.salesGoods != null
                && !TextUtils.isEmpty(goodsInfo.salesGoods.imageTextDetail)) {
            DetailActivity.launch(this, goodsInfo.salesGoods.imageTextDetail,
                    DetailActivity.TYPE_HTML, getString(R.string.one_dollar_goods_detail));
        }
    }

    @Override
    public void jump2OrderShowListPage() {
        GoodsInfoObj goodsInfo = mPresenter.getGoodsInfo();
        if (goodsInfo != null && goodsInfo.salesGoods != null && goodsInfo.salesGoods.barcode > 0) {
            OrderShowListActivity.launch(this, mPresenter.getGoodsInfo().salesGoods.barcode);
        }
    }

    @Override
    public void jump2RecordHistoryListPage() {
        GoodsInfoObj goodsInfo = mPresenter.getGoodsInfo();
        if (goodsInfo != null && goodsInfo.salesGoods != null && goodsInfo.salesGoods.barcode > 0) {
            RecordHistoryListActivity.launch(this, mPresenter.getGoodsInfo().salesGoods.barcode);
        }

    }

    @Override
    public void jump2LuckyNoIntroPage() {
        GoodsInfoObj goodsInfo = mPresenter.getGoodsInfo();
        if (goodsInfo == null || goodsInfo.salesGoods == null) {
            return;
        }
        LuckyNoIntroActivity.launch(this, goodsInfo.salesGoods.goodsNo,
                goodsInfo.salesGoods.periodsNum);
    }

    @Override
    public void jump2NextPage() {
        GoodsInfoObj goodsInfo = mPresenter.getGoodsInfo();
        if (goodsInfo == null || goodsInfo.salesGoods == null || goodsInfo.salesGoods.nextGoodsNo <= 0) {
            return;
        }
        GoodsPurchaseActivity.launch(this, goodsInfo.salesGoods.nextGoodsNo);
    }

    @Override
    public void refreshView(boolean bSuc) {
        if (bSuc) {
            mRootView.setVisibility(View.VISIBLE);
            setGoodsInfoViews();
            setPicSlideView();
            setOrderRecordView();
            setCountDownView();
            setWinningRecordView();
            setBottomPannelView();
        } else {
            mRootView.setVisibility(View.GONE);
            finish();
        }
    }

    private void setBottomPannelView() {
        GoodsInfoObj goodsInfo = mPresenter.getGoodsInfo();
        if (goodsInfo == null || goodsInfo.salesGoods == null) {
            return;
        }
        mBuyNowTv.setVisibility(
                TextUtils.isEmpty(goodsInfo.salesGoods.announcedTime) ? View.VISIBLE : View.GONE);
        mGoTv.setVisibility(
                TextUtils.isEmpty(goodsInfo.salesGoods.announcedTime) ? View.GONE : View.VISIBLE);
        mGoTv.setEnabled(goodsInfo.salesGoods.isExistNext == 1);
        mGoTv.setClickable(goodsInfo.salesGoods.isExistNext == 1);
        mGoTv.setText(goodsInfo.salesGoods.isExistNext == 1 ? getString(R.string.one_dollar_good_go)
                : getString(R.string.one_dollar_good_no_next));
        if (mBuyNowTv.getVisibility() == View.GONE && mGoTv.getVisibility() == View.GONE) {
            mBottomView.setVisibility(View.GONE);
        } else {
            mBottomView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void jump2PayPage(String goodsName, double cost, OrderObj orderObj, long periodsNum,
                             long joinNum, long goodsNo) {
        dismissPopDlg();
        PayActivity.launch(this, goodsName, cost, orderObj, periodsNum, joinNum, goodsNo);
    }

    @Override
    public void jump2LoginPage() {
        startTargetActivity(LoginPageActivity.class);
    }

    private void setWinningRecordView() {
        GoodsInfoObj goodsInfo = mPresenter.getGoodsInfo();
        if (goodsInfo == null || goodsInfo.winningRecord == null) {
            mWinningRecordView.setVisibility(View.GONE);
            return;
        }

        try {
            Date dateNow = DateUtil.stringToDate(goodsInfo.currentSystemTime,
                    DateUtil.PATTERN_DATE_TIME);
            Date dateAnnouce = DateUtil.stringToDate(goodsInfo.salesGoods.announcedTime,
                    DateUtil.PATTERN_DATE_TIME);
            if (dateAnnouce == null || dateNow == null) {
                mWinningRecordView.setVisibility(View.GONE);
            } else {
                if (dateAnnouce.after(dateNow)) {
                    mWinningRecordView.setVisibility(View.GONE);
                } else {

                    WinningRecord winningRecord = goodsInfo.winningRecord;
                    mWinningRecordView.setVisibility(View.VISIBLE);
                    if (!TextUtils.isEmpty(winningRecord.userHeadImg)) {
                        Glide.with(getApplicationContext()).load(winningRecord.userHeadImg)
                                .asBitmap().placeholder(R.drawable.blank)
                                .diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop()
                                .animate(R.anim.fade_in_image).into(mAvatarView);
                    }
                    String format = String.format(getString(R.string.one_dollar_winner),
                            winningRecord.userName);
                    mRecordWinnerTv.setText(format);
                    format = String.format(getString(R.string.one_dollar_good_periods),
                            winningRecord.periodsNum);
                    mRecordPeriodNoTv.setText(format);
                    format = String.format(getString(R.string.one_dollar_join_count),
                            winningRecord.joinNum);
                    mRecordJoinNoTv.setText(format);
                    format = String.format(getString(R.string.one_dollar_announced_time),
                            winningRecord.announcedTime);
                    mRecordAnnounceTimeTv.setText(format);
                    format = String.format(getString(R.string.one_dollar_luck_num),
                            winningRecord.luckyNum);
                    mRecordLuckNoTv.setText(format);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    private void setCountDownView() {
        GoodsInfoObj goodsInfo = mPresenter.getGoodsInfo();
        if (goodsInfo == null || goodsInfo.salesGoods == null) {
            return;
        }
        try {
            Date dateNow = DateUtil.stringToDate(goodsInfo.currentSystemTime,
                    DateUtil.PATTERN_DATE_TIME);
            Date dateAnnouce = DateUtil.stringToDate(goodsInfo.salesGoods.announcedTime,
                    DateUtil.PATTERN_DATE_TIME);
            if (dateAnnouce != null && dateNow != null && dateAnnouce.after(dateNow)) {
                mCountDownLl.setVisibility(View.GONE);
                mCountDownCv.start(0);
                mCountDownCv.setOnCountdownEndListener(this);
                mCountDownCv.setOnCountdownIntervalListener(1000, this);
            } else {
                mCountDownLl.setVisibility(View.GONE);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    private void setOrderRecordView() {
        GoodsInfoObj goodsInfo = mPresenter.getGoodsInfo();
        if (goodsInfo == null) {
            return;
        }
        if (goodsInfo.salesGoods!=null && !TextUtils.isEmpty(goodsInfo.salesGoods.createTime)){
            String format = String.format(getResources().getString(R.string.one_dollar_join_start),
                goodsInfo.salesGoods.createTime);
            mJoinStartTv.setText(format);
        }

        if (goodsInfo.orderMain == null || goodsInfo.orderMain.isEmpty()) {
            mJoinRecordList.setVisibility(View.GONE);
        } else {
            mJoinRecordList.setVisibility(View.VISIBLE);
            mJoinRecordList.setAdapter(new JoinRecordAdapter(this, goodsInfo.orderMain));
        }
    }

    private void setGoodsInfoViews() {
        GoodsInfoObj goodsInfo = mPresenter.getGoodsInfo();
        if (goodsInfo == null || goodsInfo.salesGoods == null) {
            return;
        }
        mGoodsNameTv.setText(goodsInfo.salesGoods.goodsName);
        mGoodsDesTv.setText(goodsInfo.salesGoods.desc);
        String format = String.format(getResources().getString(R.string.one_dollar_periods_num),
                goodsInfo.salesGoods.periodsNum);
        mPeriodsNumTv.setText(format);
        format = String.format(getResources().getString(R.string.one_dollar_total),
                goodsInfo.salesGoods.totalJoinNum);
        mTotalTv.setText(SpannableUtil.setHighLight(this, format, format.substring(0, 2),
                R.color.oneDollarTextBlack));
        format = String.format(getResources().getString(R.string.one_dollar_remain),
                goodsInfo.salesGoods.surplusJoinNum);
        mRemainTv.setText(SpannableUtil.setHighLight(this, format, format.substring(0, 2),
                R.color.oneDollarTextBlack));
        mProgressBar.setMax((int) goodsInfo.salesGoods.totalJoinNum);
        mProgressBar.setProgress((int) goodsInfo.salesGoods.totalJoinNum
                - (int) goodsInfo.salesGoods.surplusJoinNum);
    }

    private void setPicSlideView() {
        GoodsInfoObj goodsInfo = mPresenter.getGoodsInfo();
        List<String> configs = new ArrayList<>();
        if (goodsInfo != null && goodsInfo.salesGoods != null
                && !TextUtils.isEmpty(goodsInfo.salesGoods.goodsPic)) {
            String goodsPic = goodsInfo.salesGoods.goodsPic;
            try {
                configs = Arrays.asList(goodsPic.split(","));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        mPicSlideView.removeAllViews();
        mPicSlideView.initData(this, configs);

    }

    @Override
    public void onEnd(CountdownView cv) {
        cv.setEnabled(false);
    }

    @Override
    public void onInterval(CountdownView cv, long remainTime) {
        if (remainTime > OneDollarConstants.COUNT_DOWN_TIME) {
            mCountDownLl.setVisibility(View.GONE);
        } else {
            mCountDownLl.setVisibility(remainTime == 0 ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    protected int getThemeId() {
        return R.style.OneDollarThemeGrey;
    }

    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        int picSlideViewHeight = mTitleView.getHeight();
        if (y <= 0) {
            mTitleView.setBackgroundColor(getResources().getColor(R.color.transparent));//AGB由相关工具获得，或者美工提供
            mTitleView.setTitle("");
	        setStatusBar(getResources().getColor(R.color.oneDollarDetailBg));
        } else if (y > 0 && y <= picSlideViewHeight) {
            float scale = (float) (y) / (picSlideViewHeight);
            float alpha = (255 * scale);
            mTitleView.setBackgroundColor(Color.argb((int) alpha, 216, 13, 108));
            mTitleView.setTitle("商品详情");
	        setStatusBar(Color.argb((int) alpha, 216, 13, 108));
        } else {
            mTitleView.setBackgroundColor(getResources().getColor(R.color.oneDollarCommon));
            mTitleView.setTitle("商品详情");
	        setStatusBar(getResources().getColor(R.color.oneDollarCommon));
        }
    }

    private void setStatusBar(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
                && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

            ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
            View mChildView = mContentView.getChildAt(0);
            if (mChildView != null) {
                int statusHeight = getStatusBarHeight(this);
                mChildView.setPadding(mChildView.getPaddingLeft(), statusHeight,
                        mChildView.getPaddingRight(), mChildView.getPaddingBottom());
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();

            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(color);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
    }
}
